package com.spring.springboot.configure;

import java.util.Map;

import javax.persistence.EntityManager;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
*@author LSY
*Time: 2018年12月18日下午5:25:29
*
*
*/
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
		entityManagerFactoryRef = "entityManagerFactoryUser1",
		transactionManagerRef = "transactionManagerUser1",
		basePackages = {"com.spring.springboot.user1"}
		)
public class User1DataSourceConfigurer {

	@Autowired
	@Qualifier("user1DataSource")
	private DataSource user1DataSource;
	
	@Primary
	@Bean("entityManagerUser1")
	public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
		return entityManagerFactoryUser1(builder).getObject().createEntityManager();
	}
	
	@Primary
	@Bean("entityManagerFactoryUser1")
	public LocalContainerEntityManagerFactoryBean entityManagerFactoryUser1(EntityManagerFactoryBuilder builder) {
		return builder
				.dataSource(user1DataSource)
				.properties(getVendorProperties())
				.packages(new String("com.spring.springboot.user1"))
				.persistenceUnit("user1PersistenceUnit")
				.build();
	}
	
	@Autowired
	private JpaProperties jpaProperties;
	private Map<String, Object> getVendorProperties() {
		return jpaProperties.getHibernateProperties(new HibernateSettings());
	}
	
	@Primary
	@Bean(name = "transactionManagerUser1")
	public PlatformTransactionManager transactionManagerUser1(EntityManagerFactoryBuilder builder) {
		return new JpaTransactionManager(entityManagerFactoryUser1(builder).getObject());
	}
}
